package com.htkj.questservice;

import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class ForegroundAppDetector {
    /**
     * 获取当前前台应用包名（兼容所有Android版本）
     */
    public static String getForegroundApp(Context context) {
        // 方案1: Android 5.0+ 优先使用UsageStatsManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (checkUsageStatsPermission(context)) {
                String packageName = getForegroundFromUsageStats(context);
                if (!TextUtils.isEmpty(packageName))  {
                    return packageName;
                }
            }
        }

        // 方案2: Android 4.0~9.0 使用ActivityManager（部分厂商可能限制）
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            String packageName = getForegroundFromRunningTasks(context);
            if (!TextUtils.isEmpty(packageName))  {
                return packageName;
            }
        }

        // 方案3: 备用方案（通过反射或辅助功能）
        return getForegroundByAlternative(context);
    }

    // ==== 具体实现方法 ====

    /**
     * 通过UsageStatsManager获取（Android 5.0+）
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private static String getForegroundFromUsageStats(Context context) {
        UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        long endTime = System.currentTimeMillis();
        long beginTime = endTime - 1000 * 60; // 查询最近60秒的数据
        List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,  beginTime, endTime);

        if (stats != null) {
            SortedMap<Long, UsageStats> sortedMap = new TreeMap<>();
            for (UsageStats usageStats : stats) {
                sortedMap.put(usageStats.getLastTimeUsed(),  usageStats);
            }
            if (!sortedMap.isEmpty())  {
                return sortedMap.get(sortedMap.lastKey()).getPackageName();
            }
        }
        return null;
    }

    /**
     * 通过ActivityManager.getRunningTasks 获取（Android 4.0~9.0）
     */
    @SuppressWarnings("deprecation")
    private static String getForegroundFromRunningTasks(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty())  {
            return tasks.get(0).topActivity.getPackageName();
        }
        return null;
    }

    /**
     * 备用方案（通过反射或辅助功能）
     */
    private static String getForegroundByAlternative(Context context) {
        // 可扩展：接入AccessibilityService或厂商特定API
        return "unknown";
    }

    /**
     * 检查是否已授予UsageStats权限
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static boolean checkUsageStatsPermission(Context context) {
        AppOpsManager appOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(
                AppOpsManager.OPSTR_GET_USAGE_STATS,
                android.os.Process.myUid(),
                context.getPackageName()
        );
        return mode == AppOpsManager.MODE_ALLOWED;
    }

    /**
     * 跳转到UsageStats权限授权页面
     */
    public static void requestUsageStatsPermission(Context context) {
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}
